// Copyright 2020 Jebbs. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

import { createWebviewPanel } from '../../webviewPanel';
import { context } from "../common/context";
import { sketch } from "../../sketch";
import { getResourcePath } from '../helpers/helper';
import { uuidv4 } from '../../webviewPanel/keepAround';

export function markNotebar() {
    const panel = createWebviewPanel({
        identifier: 'co.jebbs.sketch-meaxure.notebar',
        url: getResourcePath() + "/panel/notebar.html",
        acceptsFirstMouse: true,
        width: 220,
        height: 120,
    });
    if (!panel) return undefined;

    panel.onDidReceiveMessage('change', (txt: string) => {
        let selection = context.selection;

        if (selection.length <= 0) {
            sketch.Settings.setDocumentSettingForKey(context.document, 'mexure-note', txt);
        } else {
            selection.layers.forEach(l => sketch.Settings.setLayerSettingForKey(l, 'mexure-note', txt));
        }
    });
    panel.show();
}

export function handleSelect() {
    let layer = context.selection.layers[0];
    let txt = '';
    if (layer) {
        txt = sketch.Settings.layerSettingForKey(layer, 'mexure-note') || '';
    }
    let panel = NSThread.mainThread().threadDictionary()['co.jebbs.sketch-meaxure.notebar'];
    if (panel && panel.contentView) {
        let subviews = panel.contentView().subviews();
        let webView = null
        for (let i = 0; i < subviews.length; i += 1) {
            if (
                !webView &&
                // @ts-ignore
                !subviews[i].isKindOfClass(WKInspectorWKWebView) &&
                // @ts-ignore
                subviews[i].isKindOfClass(WebView)
            ) {
                webView = subviews[i]
            }
        }
        if (webView) {
            let windowObject = webView.windowScriptObject();
            let script = `
            meaxure.raiseReceiveMessageEvent("${encodeURIComponent(JSON.stringify({
                __SERVER_MESSAGE_ID__: uuidv4(),
                __MESSAGE_TYPE__: 'set-note',
                message: txt,
            }))}");
            `
            windowObject.evaluateWebScript(script);
        }
    }
}
